//
//  CZPhotoBrowserModalAnimation.swift
//  GZWeibo666
//
//  Created by iOS on 15/12/9.
//  Copyright © 2015年 itcast. All rights reserved.
//

import UIKit

class CZPhotoBrowserModalAnimation: NSObject, UIViewControllerAnimatedTransitioning {

    func transitionDuration(transitionContext: UIViewControllerContextTransitioning?) -> NSTimeInterval {
        return 0.5
    }
    
    // 实现这个方法后,需要手动添加modal出来控制的view到容器视图上面,还要通知系统转场动画完成
    func animateTransition(transitionContext: UIViewControllerContextTransitioning) {
        // 获取到modal出来的控制器的view
        let toView = transitionContext.viewForKey(UITransitionContextToViewKey)!
        
        // 添加到容器视图
        transitionContext.containerView()?.addSubview(toView)
        
        // 获取modal出来的控制器
        let toViewController = transitionContext.viewControllerForKey(UITransitionContextToViewControllerKey) as! CZPhotoBrowserViewController
        
        // 获取到过渡视图
        let tempImageView = toViewController.modalTempImageView()
        
        // 将过渡视图添加到window
//        UIApplication.sharedApplication().keyWindow?.addSubview(tempImageView)
        
        // 添加到容器视图
        transitionContext.containerView()?.addSubview(tempImageView)
        
        // 隐藏collectionView
        toViewController.collectionView.hidden = true
        
        // 淡入
        toView.alpha = 0
        
        UIView.animateWithDuration(transitionDuration(transitionContext), animations: { () -> Void in
            // 动画到大图的位置
            tempImageView.frame = toViewController.moadalTargetFrame()
            
            toView.alpha = 1
            
            }) { (_) -> Void in
                // 显示collectionView
                toViewController.collectionView.hidden = false
                
                // 移除过渡视图
                tempImageView.removeFromSuperview()
                
                // 一定要记住调用,告诉系统转场完成
                transitionContext.completeTransition(true)
        }
    }
}
